package com.yz.jdd.module.main.fragment;

import static android.os.Environment.DIRECTORY_PICTURES;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.trello.rxlifecycle.ActivityEvent;
import com.trello.rxlifecycle.FragmentLifecycleProvider;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yunzong.wifi.WifiSupport;
import com.yunzong.wifi.netconfig.SmartConfig;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseFragment;
import com.yz.jdd.base.activity.PhotoViewActivity;
import com.yz.jdd.base.entity.Image;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.AuthResult;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.FileUtils;
import com.yz.jdd.base.utils.GsonUtils;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.ProviderUtil;
import com.yz.jdd.module.cashier.CashierActivity;
import com.yz.jdd.module.help.HelpActivity;
import com.yz.jdd.module.launch.model.AppVersion;
import com.yz.jdd.module.login.view.LoginActivity;
import com.yz.jdd.module.main.MessageActivity;
import com.yz.jdd.module.main.OrderActivity;
import com.yz.jdd.module.scan.view.ScanActivity;
import com.yz.jdd.module.settings.SettingsActivity;
import com.yz.jdd.module.upgrade.DownLoadDialogActivity;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.response.Response_upgrade;
import com.yz.jdd.photo.app.TakePhoto;
import com.yz.jdd.photo.app.TakePhotoImpl;
import com.yz.jdd.photo.compress.CompressOptions;
import com.yz.jdd.photo.entity.Compress;
import com.yz.jdd.photo.entity.Crop;
import com.yz.jdd.photo.entity.MaxSize;
import com.yz.jdd.photo.entity.Photo;
import com.yz.jdd.photo.model.CropOptions;
import com.yz.jdd.photo.model.InvokeParam;
import com.yz.jdd.photo.model.LubanOptions;
import com.yz.jdd.photo.model.TContextWrap;
import com.yz.jdd.photo.model.TImage;
import com.yz.jdd.photo.model.TResult;
import com.yz.jdd.photo.model.Upload;
import com.yz.jdd.photo.permission.InvokeListener;
import com.yz.jdd.photo.permission.PermissionManager;
import com.yz.jdd.photo.permission.TakePhotoInvocationHandler;
import com.yz.jdd.photo.utils.TConstant;
import com.yz.jdd.photo.utils.TImageFiles;
import com.yz.jdd.photo.utils.TUtils;
import com.yz.jdd.service.PlayerMusicService;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;
import com.yz.jdd.webview.H5BridgeOtherActivity;
import com.yz.jdd.webview.HostJsScope;
import com.yz.jdd.webview.download.DataCleanManager;
import com.yz.jdd.webview.download.FetchUtil;
import com.yz.jdd.webview.download.H5DownFileUtils;
import com.yz.jdd.webview.entity.PayResult;
import com.yz.jdd.webview.entity.UserInfo;
import com.yz.jdd.webview.net.H5Subscription;
import com.yz.jdd.widget.BottomDialog;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.functions.Action1;

public class H5Fragment extends BaseFragment implements TakePhoto.TakeResultListener, InvokeListener {
    public static final String TAG = "lkf";
    private BridgeWebView webview;
    private LinearLayout errorLayout;
    private String main_url = "";//跳转到该页面的url 由上一个页面返回
    private List<String> apiQueue = new ArrayList<String>();
    LinearLayout loading_layout;
    SmartConfig smartConfig;
    private H5Fragment.MyReceiver myReceiver;
    private IntentFilter intentFilter;
    private CallBackFunction takePictureCallBackFunction;
    private CallBackFunction selectPictureCallBackFunction;
    private CallBackFunction photoviewCallBackFunction;
    private CallBackFunction uploadPictureCallBackFunction;
    private CallBackFunction savePictureCallBackFunction;
    private CallBackFunction scanCallBackFunction;
    private CallBackFunction authV2CallBackFunction;
    private CallBackFunction payV2CallBackFunction;
    private TakePhoto takePhoto;
    private static String apiName;
    private static final int SDK_PAY_FLAG = 2;
    private InvokeParam invokeParam;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "", true,
                            "tradePay", payResult, payV2CallBackFunction);
                    if (payV2CallBackFunction != null) {
                        payV2CallBackFunction = null;
                    }
                    break;
                }
                case 1: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "", true, "authV2", authResult.getUserId(), authV2CallBackFunction);
                    } else {
                        // 其他状态值则为授权失败
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "授权失败", true, "authV2", "", authV2CallBackFunction);
                    }
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);

    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.d("--- resultCode="+requestCode+ " resultCode="+resultCode);
        if (requestCode == 5 && resultCode == 5) {
            if (data != null) {
                String code = data.getStringExtra("code");
                if (!TextUtils.isEmpty(code)) {
//                    result: {error, barCode, qrCode, cardNumber}错误码（10： 用户取消， 11： 操作失败）
                    HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "scan", code, scanCallBackFunction);
                } else {
                    if (!TextUtils.isEmpty(data.getStringExtra("cancel"))) {
                        HostJsScope.h5PostLocalCallBack(webview, "10", "", false, "scan", null, scanCallBackFunction);
                    } else {
                        HostJsScope.h5PostLocalCallBack(webview, "11", "", false, "scan", null, scanCallBackFunction);
                    }
                }
            }
        } else {
            getTakePhoto().onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //注册RxBus事件监听
    void registerRxBusEvents() {
        RxBus.with(this).setEvent(Events.EVENT_IMAGEPREVIEW_RESULT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events != null) {
                    if (Events.EVENT_IMAGEPREVIEW_RESULT.equals(events.code)) {
                        Response_Base response_base = events.getContent();
                        if (response_base != null) {
                            HostJsScope.h5PostLocalCallBack(webview, response_base.getCode(), response_base.getMsg(), response_base.success(), "viewPicture", response_base, photoviewCallBackFunction);
                            if (photoviewCallBackFunction != null) {
                                photoviewCallBackFunction = null;
                            }
                        }
                    }
                }
            }
        }).create();

        //上传图回调h5
        RxBus.with(this).setEvent(Events.EVENT_UPLOADPICTURE_RESULT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events != null) {
                    if (Events.EVENT_UPLOADPICTURE_RESULT.equals(events.code)) {
                        String str = events.getContent();
                        LogUtils.d("str :: " + str);
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JsonObject returnData = new JsonParser().parse(str).getAsJsonObject();
                                if (returnData != null) {
                                    HostJsScope.h5PostLocalCallBack(webview, "0", "图片上传成功", true, "uploadPicture", returnData, uploadPictureCallBackFunction);
                                    if (uploadPictureCallBackFunction != null) {
                                        uploadPictureCallBackFunction = null;
                                    }
                                } else {
                                    HostJsScope.h5PostLocalCallBack(webview, "-1", "图片上传失败", false, "uploadPicture", str, uploadPictureCallBackFunction);
                                    if (uploadPictureCallBackFunction != null) {
                                        uploadPictureCallBackFunction = null;
                                    }
                                }
                            } catch (Exception e) {
                                HostJsScope.h5PostLocalCallBack(webview, "-1", "图片上传失败", false, "uploadPicture", str, uploadPictureCallBackFunction);
                                if (uploadPictureCallBackFunction != null) {
                                    uploadPictureCallBackFunction = null;
                                }
                            }
                        } else {
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "图片格式不支持", false, "uploadPicture", str, uploadPictureCallBackFunction);
                            if (uploadPictureCallBackFunction != null) {
                                uploadPictureCallBackFunction = null;
                            }
                        }
                    }

                }
            }
        }).create();
    }

    @Override
    public void takeSuccess(TResult result) {
        LogUtils.d("takeSuccess result==== " + result);

        if (result != null) {

            if (takePictureCallBackFunction != null) {
                LogUtils.d("takeSuccess result====222 " );

                TImage image = result.getImage();
                if (image != null) {

                    String imagePath = image.getCompressPath();
                    LogUtils.d("takeSuccess imagePath==== " + imagePath);

                    if (TextUtils.isEmpty(imagePath)) {
                        imagePath = image.getOriginalPath();
                    }

                    if (!TextUtils.isEmpty(imagePath)) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "成功", true, apiName, "file://" + imagePath, takePictureCallBackFunction);
                        takePictureCallBackFunction = null;
                    }
                }
            }

            //选择图片裁剪返回数据
            if (selectPictureCallBackFunction != null) {
                List<TImage> images = result.getImages();

                List<String> imagePaths = new ArrayList<>();
                if (images != null && images.size() > 0) {
                    for (TImage tImage : images) {
                        if (tImage != null) {
                            String imagePath = tImage.getCompressPath();
                            if (TextUtils.isEmpty(imagePath)) {
                                imagePath = tImage.getOriginalPath();
                            }

                            imagePaths.add("file://" + imagePath);
                            LogUtils.d(" images ==== " + imagePath);
                        }
                    }
                    if ( imagePaths.size() > 0) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "成功", true, apiName, imagePaths, selectPictureCallBackFunction);
                        selectPictureCallBackFunction = null;
                    }
                }

            }
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        if (takePictureCallBackFunction != null) {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, apiName, "", takePictureCallBackFunction);
            takePictureCallBackFunction = null;
        }
        if (selectPictureCallBackFunction != null) {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, apiName, "", selectPictureCallBackFunction);
            selectPictureCallBackFunction = null;
        }
    }

    @Override
    public void takeCancel() {
        if (takePictureCallBackFunction != null) {
            takePictureCallBackFunction = null;
        }
        if (selectPictureCallBackFunction != null) {
            selectPictureCallBackFunction = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(requireActivity(), type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    // 多进程,广播接收消息
    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content = intent.getStringExtra("event");
            if (!TextUtils.isEmpty(content)) {
                if (Events.EVENT_VOICE_BROADCAT.equals(content)) {
                    requireActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.NEW_ORDER_EVENT);");
                        }
                    });
                }
            } else {
                if (Events.EVENT_LOAD_URL.equals(content)) {
                    dismissLoading();
                    webview.loadUrl(main_url);
                }
            }
        }
    }


    private void init(View view) {

        String sessionId = requireActivity().getIntent().getStringExtra("sessionId");
        if (!PreferencesUtils.getString(requireActivity(), BaseConfigs.PREF_SESSIONID, "").equals(sessionId)) {
            if (!TextUtils.isEmpty(sessionId)) {
                PreferencesUtils.putString(requireActivity(), BaseConfigs.PREF_SESSIONID, sessionId);
            }
        }
        loading_layout = (LinearLayout) view.findViewById(R.id.loading_layout);
        String loading = requireActivity().getIntent().getStringExtra("loading");
        if (!TextUtils.isEmpty(loading)) {
            loading_layout.setVisibility(View.GONE);
        }

        webview = (BridgeWebView) view.findViewById(R.id.webview);
        errorLayout = (LinearLayout) view.findViewById(R.id.error_layout);
        errorLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isErrorPage = false;
                webview.reload();
            }
        });
        Bundle args = getArguments();
        if (args != null) {
            main_url = args.getString(Constants.H5_WEB_URL, "");
        }
        initWebView();

        myReceiver = new H5Fragment.MyReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("updateH5Page");
        requireActivity().registerReceiver(myReceiver, intentFilter);
        registerRxBusEvents();
    }


    @Override
    public void onResume() {
        super.onResume();
        //界面被唤醒的时候调用
        Log.i("lkf", "onResume");
        if (webview != null) {
            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.RESUME_EVENT);");
        }
        if (getActivity() != null) {
            getActivity().stopService(new Intent(requireActivity(), PlayerMusicService.class));
        }
    }


    private void initWebView() {

        //规则在定义请求接口的时候需要首先调用,apiQueue.add("sendHttpRequest"); 因为js会首先调用checkApi接口,检验Android本地方法是否存在
        apiQueue.add("sendHttpRequest"); //发送http请求
        apiQueue.add("openNativePage");
        apiQueue.add("routerBeforeEach");
        apiQueue.add("takePicture");//拍照裁剪接口
        apiQueue.add("selectPicture");//选择图片裁剪接口
        apiQueue.add("viewPicture");//图片预览接口
        apiQueue.add("uploadPicture");//上传图片
        apiQueue.add("logout");//退出登录接口
        apiQueue.add("getUserInfo");//获取用户信息
        apiQueue.add("exitApp");//js调用客户端前台切换到后台运行
        apiQueue.add("sendHttpRequest"); //发送http请求
        apiQueue.add("dial");//拨打电话
        apiQueue.add("login");//跳转登录
        apiQueue.add("setTitle");//设置页面的标题栏，包括主标题，副标题以及标题菜单项
        apiQueue.add("setOptionMenu");//设置标题栏右边的按钮属性。该接口仅负责设置，需要额外调用showOptionMenu保证该按钮的显示
        apiQueue.add("showOptionMenu");//显示标题栏右边的按钮属性
        apiQueue.add("hideOptionMenu");//隐藏标题栏右边的按钮属性
        apiQueue.add("pushWindow");//用来打开一个新的页面，系统自带转场动画。
        //与location.href的区别，类同于PC浏览器的新开标签页，每个window都是一个新的标签页，因此原页面仅仅是被压到后台，状态始终保持，JS也会继续运行。
        apiQueue.add("popWindow");//popWindow用来关闭当前页面，自动返回到上一个
        apiQueue.add("setBackOption");
        apiQueue.add("openApp");//打开三方app
        apiQueue.add("testVoiceBroadcast");
        apiQueue.add("savePicture");
        apiQueue.add("scan");
        apiQueue.add("authV2");//调用支付宝授权
        apiQueue.add("tradePay");//支付宝支付
        apiQueue.add("getNearbyWIFI");//1.获取附近wifi
        apiQueue.add("startBroadcast");//2.开启广播
        apiQueue.add("stopBroadcast");//3.关闭广播
        apiQueue.add("getAppVersion");//获取当前app版本号
        apiQueue.add("upgradeApp");//更新app版本
        apiQueue.add("openDetectVoiceRight");//语音播报故障诊断
        apiQueue.add("updateNativePage");//发消息给本地页面
        apiQueue.add("setServerUrl");//设置服务地址
        apiQueue.add("removeH5Source");//删除H5资源
        apiQueue.add("resetAll");//重置所有
        apiQueue.add("downLoadH5Source");//下载H5资源
        apiQueue.add("hideSplash");//隐藏
        apiQueue.add("writeLogToApp");//写日志接口
        apiQueue.add("openWifi");
        apiQueue.add("shardBySystem");


        // 设置具体WebViewClient
        webview.setWebViewClient(new H5Fragment.MyWebViewClient(webview));
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {

            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.i(TAG, "onReceivedTitle:title ------>" + title);
                if (title.contains("404")) {
                    showErrorPage();
                }
            }
        });
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAllowFileAccessFromFileURLs(true);
        webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        //极速云所需配置
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//支持js调用window.open方法
        webview.getSettings().setSupportMultipleWindows(false);// 设置允许开启多窗口
        String ua = webview.getSettings().getUserAgentString();
        webview.getSettings().setUserAgentString(ua + ";androidapp/cross-bmios" + ";webJSY/1.0.0");
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.LOW);
        webview.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        webview.getSettings().setTextZoom(100);
        webview.loadUrl(main_url);


        webview.registerHandler("checkApi", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                Response_Base response_base = new Response_Base();
                String code = "";
                String msg = "";
                boolean success;
                if (jsonObject != null && jsonObject.get("apiName") != null) {
                    String str = jsonObject.get("apiName").getAsString();
                    Log.i("lkf", "H5Fragment apiName=" + str);
                    if (!TextUtils.isEmpty(str) && apiQueue.contains(str)) {
                        //说明接口存在
                        code = "0";
                        msg = "支持该接口";
                        success = true;
                        Log.i("lkf", "H5Fragment 支持该接口");

                    } else {
                        //接口不存在
                        code = "-1";
                        msg = "接口不存在";
                        success = false;
                        Log.i("lkf", "H5Fragment 接口不存在");

                    }
                } else {
                    //data格式有问题
                    code = "-1";
                    msg = "数据格式有问题";
                    success = false;
                    Log.i("lkf", "H5Fragment 数据格式有问题");

                }
                LogUtils.d("--- code="+code+" msg="+msg);
                response_base.setResultObject(null);
                HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "checkApi", response_base, function);

            }
        });
        webview.registerHandler("sendHttpRequest", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                HostJsScope jsScope = new HostJsScope();
                jsScope.resultCallBack(webview, "sendHttpRequest", data, function);
            }
        });
        webview.registerHandler("openNativePage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Log.e("lkf", "--- openNativePage data = " + data);
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("pageName") != null) {
                    String pageName = jsonObject.get("pageName").getAsString();
                    if ("receivingPayments".equals(pageName)) {//付款码
                        Intent intent = new Intent(getActivity(), CashierActivity.class);
                        startActivity(intent);
                    } else if ("scanCode".equals(pageName)) {
                        LogUtils.d("--- scanCode");

                        Intent intent = new Intent(requireActivity(), ScanActivity.class);
                        intent.putExtra("title", "扫描设备二维码");
                        intent.putExtra("from", "homeFragment");
                        startActivity(intent);

                    } else if ("message".equals(pageName)) {
                        Intent intent = new Intent(requireActivity(), MessageActivity.class);
                        startActivity(intent);

                    } else if ("order".equals(pageName)) {
                        Intent intent = new Intent(requireActivity(), OrderActivity.class);
                        startActivity(intent);
                    } else if ("settings".equals(pageName)) {
                        Intent intent = new Intent(requireActivity(), SettingsActivity.class);
                        startActivity(intent);
                    } else if ("hideBottomNav".equals(pageName)) {
                        RxBus.getInstance().send(Events.EVENT_HIDE_SHOW_BOTTOM_NAV, false);
                    } else if ("showBottomNav".equals(pageName)) {
                        RxBus.getInstance().send(Events.EVENT_HIDE_SHOW_BOTTOM_NAV, true);
                    }
                }
            }
        });

        webview.registerHandler("routerBeforeEach", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("toName") != null) {
                    String toName = jsonObject.get("toName").getAsString();
                }
            }
        });

        //调用系统分享
        webview.registerHandler("shardBySystem", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                String filePath = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "" + "/yz" + System.currentTimeMillis() + ".jpg";
                File takeImageFile = new File(filePath);
                if (jsonObject != null && jsonObject.get("imageBase64Str") != null) {
                    String imageBase64Str = jsonObject.get("imageBase64Str").getAsString();
                    Log.e("lkf", imageBase64Str);
                    int index = imageBase64Str.indexOf(",");
                    String subStr = imageBase64Str.substring(index + 1);
                    Log.e("lkf", subStr);
                    try {
                        byte[] buffer = Base64.decode(subStr.getBytes(), Base64.DEFAULT);
                        FileOutputStream out = new FileOutputStream(takeImageFile);
                        out.write(buffer);
                        out.close();
                        Log.e("lkf", takeImageFile.length() + "");
                    } catch (Exception e) {
                        Log.e("lkf", e.toString());
                        e.printStackTrace();
                    }

                }

                Uri uri;
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    uri = Uri.fromFile(takeImageFile);
                } else {
                    //7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider,并且这样可以解决MIUI系统上拍照返回size为0的情况
                    uri = FileProvider.getUriForFile(requireContext(), ProviderUtil.getFileProviderName(requireContext()), takeImageFile);
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                intent.setType("image/*");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(Intent.createChooser(intent, ""));
            }
        });

        //打开wifi
        webview.registerHandler("openWifi", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                startActivity(wifiSettingsIntent);
            }
        });
        //隐藏
        webview.registerHandler("hideSplash", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                loading_layout.setVisibility(View.GONE);
            }
        });
        webview.registerHandler("writeLogToApp", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("text") != null) {
                    String text = jsonObject.get("text").getAsString() + "";
                }
            }
        });

        //设置服务地址url，清除版本号，删除资源重启
        webview.registerHandler("setServerUrl", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(url)) {
                        DataCleanManager.cleanApplicationData(requireContext());
                        PreferencesUtils.putString(
                                requireContext(), BaseConfigs.STRING_SERVER_URL, url);
                        PreferencesUtils.putString(
                                requireContext(), BaseConfigs.STRING_GUID, "");
                        //删除资源
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }
            }
        });

        //删除h5资源，删除解压文件
        webview.registerHandler("removeH5Source", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DataCleanManager.cleanApplicationData(requireContext());
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });

        //重置所有，删除data
        webview.registerHandler("resetAll", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DataCleanManager.cleanApplicationData(requireContext());
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });


        //解压h5资源
        webview.registerHandler("downLoadH5Source", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String downLoadUrl = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(downLoadUrl)) {
                        FetchUtil.downLoadH5zip(downLoadUrl);
                    }
                }
            }
        });

        //获取附近wifi
        webview.registerHandler("getNearbyWIFI", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                XXPermissions.with(requireActivity()).permission(
                        Permission.ACCESS_COARSE_LOCATION,
                        Permission.ACCESS_FINE_LOCATION
                ).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
                            dismissTopDialog();
                            if (WifiSupport.isOpenWifi(requireContext())) {
                                List<ScanResult> scanResults = WifiSupport.noSameName(WifiSupport.getWifiScanResult(requireContext()));
                                if (scanResults != null) {
                                    List<String> wifiList = new ArrayList<>();
                                    for (ScanResult scanResult : scanResults) {
                                        wifiList.add(scanResult.SSID);
                                    }
                                    if (wifiList.size() > 0) {
                                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS,
                                                "", true, "getNearbyWIFI", wifiList, function);
                                    } else {
                                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL,
                                                "未取到wif信息", false, "getNearbyWIFI", null, function);
                                    }

                                }

                            } else {
                                //打开wifi
                                final PublicDialog publicDialog = new PublicDialog(requireContext());
                                publicDialog.setMessage("请先开启手机Wi-Fi功能");
                                publicDialog.setRightBtn("去开启",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //直接进入手机中的wifi网络设置界面
                                                publicDialog.dismiss();
                                            }
                                        });
                                publicDialog.show();
                            }

                        }

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        dismissTopDialog();
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL,
                                "未开启wifi权限", false, "getNearbyWIFI", null, function);
                    }
                });
                if (!XXPermissions.isHasPermission(requireContext(), Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION)) {
                    showTopDialog("为了您能正常使用玛卡龙、快小盒相关功能，请向您申请【定位】功能以获取附近WIFI，完成配网工作，保证功能的正常使用！");
                }
            }
        });
        //开启广播
        webview.registerHandler("startBroadcast", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("content") != null) {

                    String contentString = jsonObject.get("content").getAsString();
                    if (!TextUtils.isEmpty(contentString)) {
                        JsonObject content = HostJsScope.Json2JsonObject(contentString);
                        String name = content.get("name").getAsString() + "";
                        String password = content.get("password").getAsString() + "";
                        if (smartConfig != null) {
                            smartConfig.stop();
                        }
                        smartConfig = new SmartConfig(requireContext());
                        smartConfig.start(name, password);
                    }
                }
            }
        });
        //关闭广播
        webview.registerHandler("stopBroadcast", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (smartConfig != null)
                    smartConfig.stop();
            }
        });

        //跳转登录关闭其他页面
        webview.registerHandler("login", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                RxBus.getInstance().send(Events.EVENT_302CODE, "");
                Intent intent = new Intent(requireContext(), LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                intent.putExtra("logout", "1");

                startActivity(intent);

            }
        });

        //发消息给本地页面
        webview.registerHandler("updateNativePage", (data, function) -> {
            Intent intent = new Intent("updateNativePage");
            if (data.contains("newsPage")) {
                intent.putExtra("page", "newsPage");
                requireActivity().sendBroadcast(intent);
            } else if (data.contains("orderPage")) {
                //发消息,刷新首页/列表数据
                intent.putExtra("page", "orderPage");
                requireActivity().sendBroadcast(intent);
            } else {
                startActivity(new Intent(requireActivity(), HelpActivity.class));
            }
        });

        webview.registerHandler("openDetectVoiceRight", (data, function) -> {
            Intent intent = new Intent(requireContext(), HelpActivity.class);
            startActivity(intent);
        });
        webview.registerHandler("openApp", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";
                    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        try {
                            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                            HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "openApp", "", function);
                        } catch (Exception e) {
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "", false, "openApp", "", function);
                        }

                    }

                }

            }
        });

        //测试语音
        webview.registerHandler("testVoiceBroadcast", (data, function) -> {
            try {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("text") != null) {
                    String text = jsonObject.get("text").getAsString() + "";

                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent(text);
                    if (XXPermissions.isHasPermission(requireContext(), Permission.READ_PHONE_STATE)) {
                        try {
                            LogUtils.e("=== SpeechUtilOffline play Content:" + orderVoice.getContent());
                            SpeechUtilOffline.getInstance(requireContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("语音播报成功");
                if (XXPermissions.isHasPermission(requireContext(), Permission.READ_PHONE_STATE)) {
                    try {
                        LogUtils.e("=== SpeechUtilOffline play Content:" + orderVoice.getContent());
                        SpeechUtilOffline.getInstance(requireContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                    } catch (Exception e1) {
                        e.printStackTrace();
                    }
                }
            }
        });


        /**
         * //用来打开一个新的页面，系统自带转场动画。
         * 与location.href的区别，类同于PC浏览器的新开标签页，每个window都是一个新的标签页，
         * 因此原页面仅仅是被压到后台，状态始终保持，JS也会继续运行。
         * {
         url: 'https://m.taobao.com/',
         param: {
         title: {
         title: '标题’,
         background：”#ff0000”,   //标题栏背景色
         color：”#ffff00”         //标题栏前景色
         },
         showOptionMenu: false  //缺省  可不传，默认为false
         }
         */
        webview.registerHandler("pushWindow", (data, function) -> {
            LogUtils.e(data);
            if (TextUtils.isEmpty(data))
                return;
            JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
            if (jsonObject != null) {
                Intent intent = new Intent(requireContext(), H5BridgeOtherActivity.class);

                if (jsonObject.get("param") != null) {
                    JsonObject paramJsonObject = (JsonObject) jsonObject.get("param");
                    if (paramJsonObject != null) {
                        try {
                            JsonObject titleJsonObject = (JsonObject) paramJsonObject.get("title");
                            if (titleJsonObject != null) {
                                String titleStr = titleJsonObject.get("title").getAsString() + "";
                                if (!TextUtils.isEmpty(titleStr))
                                    intent.putExtra("title", titleStr);
                                String backgroundStr = titleJsonObject.get("background").getAsString() + "";
                                if (!TextUtils.isEmpty(backgroundStr))
                                    intent.putExtra("background", backgroundStr);

                                String colorStr = titleJsonObject.get("color").getAsString() + "";
                                if (!TextUtils.isEmpty(colorStr))
                                    intent.putExtra("color", colorStr);
                            } else {
                                intent.putExtra("showTop", "showTop");
                            }
                        } catch (Exception e) {
                            Log.e("lkf", e.toString());
                            intent.putExtra("showTop", "showTop");
                        }
                    }


                }
                String parme = "";
                if (jsonObject.get("suffixParams") != null) {
                    parme = jsonObject.get("suffixParams").getAsString() + "";
                }
                if (jsonObject.get("url") != null) {
                    String openUrl = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(openUrl)) {
                        String target = "";
                        if (jsonObject.get("target") != null)
                            target = jsonObject.get("target").getAsString() + "";

                        if ("local".equals(target)) {
                            openUrl = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + openUrl + "?s=" +
                                    PreferencesUtils.getString(requireContext(), BaseConfigs.PREF_SESSIONID) +
                                    "&statusBarHeight=0&android=4.1" + "&SDK=" + Build.VERSION.SDK_INT + parme
                                    + "&url=" + PreferencesUtils.getString(requireContext(), BaseConfigs.STRING_SERVER_URL, Constants.SERVER_URL);

                        }
                        if (!TextUtils.isEmpty(parme))
                            openUrl = openUrl + "&" + parme;
                        intent.putExtra(Constants.H5_WEB_URL, openUrl);
                        String sessionId = PreferencesUtils.getString(requireContext(), BaseConfigs.PREF_SESSIONID);
                        intent.putExtra("sessionId", sessionId);
                        startActivity(intent);
                    }

                }

            }
        });


        //popWindow用来关闭当前页面，自动返回到上一个
        webview.registerHandler("popWindow", (data, function) -> requireActivity().finish());

        //获取当前app版本号
        webview.registerHandler("getAppVersion", (data, function) -> HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "getAppVersion", AppUtils.getVerName(requireContext()), function));
        //更新app版本
        webview.registerHandler("upgradeApp", (data, function) -> {
            Log.e("data", data);
            Response_upgrade response_upgrade = (Response_upgrade) GsonUtils.json2Obj(data, Response_upgrade.class);
            if (response_upgrade != null && response_upgrade.getAppVersion() != null) {
                AppVersion appVersion = response_upgrade.getAppVersion();
                String downLoadUrl = appVersion.getAddress();
                showVersionUpdate(appVersion, downLoadUrl);
            }
        });

        //拨打电话
        webview.registerHandler("dial", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        LogUtils.d("--- h5 dial");
                        if (TextUtils.isEmpty(data))
                            return;
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        if (jsonObject != null && jsonObject.get("mobile") != null) {
                            String mobile = jsonObject.get("mobile").getAsString() + "";
                            BottomDialog bottomDialog = new BottomDialog(requireContext());
                            bottomDialog.setPhoneNumber("呼叫 " + mobile);
                            bottomDialog.setConfirmListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mobile));
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);
                                    Response_Base response_base = new Response_Base();
                                    response_base.setCode("0");
                                    response_base.setSuccess(true);
                                    response_base.setResultObject(null);
                                    HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "dial", response_base, function);
                                    bottomDialog.dismiss();
                                }
                            });
                            bottomDialog.show();

                        }

                    }
                });
        //发送http请求
        webview.registerHandler("sendHttpRequest", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        HostJsScope jsScope = new HostJsScope();
                        jsScope.resultCallBack(webview, "sendHttpRequest", data, function);
                    }
                });
        //切换app到后台
        webview.registerHandler("exitApp", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(intent);
                    }
                });
        webview.registerHandler("getUserInfo", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        Response_Base response_base = new Response_Base();
                        String code = "0";
                        String msg = "获取用户信息";
                        boolean success = true;
                        UserInfo userInfo = new UserInfo();
                        userInfo.setSessionId(PreferencesUtils.getString(requireContext(), BaseConfigs.PREF_SESSIONID));
                        HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "getUserInfo", userInfo, function);

                    }
                });
        //退出登录
        webview.registerHandler("logout", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, final CallBackFunction function) {
                        H5Subscription.h5LogoutSubscription(new ApiCallback() {
                            @Override
                            public void onSuccess(Response_Base response_baseModel) {
                                PreferencesUtils.putString(requireContext(), BaseConfigs.STRING_MOVEKOUBEI, "0");
                                RxBus.getInstance().send(Events.EVENT_302CODE, "");
                                Intent intent = new Intent(requireContext(), LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                                intent.putExtra("logout", "1");

                                startActivity(intent);
                                Response_Base response_base = new Response_Base();
                                response_base.setCode("0");
                                response_base.setSuccess(true);
                                response_base.setResultObject(null);
                                HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "logout", response_base, function);
                            }

                            @Override
                            public void onNeedLogin(String msg) {
                            }

                            @Override
                            public void onFail(Response_Base response_baseModel) {
                                if (response_baseModel != null) {
                                    String msg = response_baseModel.getMsg();
                                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, "logout", "", function);
                                }
                            }
                        });

                    }
                });
        //拍照并裁切接口
        webview.registerHandler("takePicture", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        LogUtils.d("--- h5 takePicture");
                        Photo photo = (Photo) GsonUtils.json2Obj(data, Photo.class);
                        TakePhoto takePhoto = getTakePhoto();
                        if (photo != null) {
                            Compress compress = photo.getCompress();
                            MaxSize maxSize = photo.getMaxSize();
                            if (compress != null || maxSize != null) {
                                LubanOptions.Builder builder = new LubanOptions.Builder();
                                if (maxSize != null) {
                                    if (!TextUtils.isEmpty(maxSize.getWidth()) && !TextUtils.isEmpty(maxSize.getHeight())) {

                                        builder.setMaxWidth(Integer.parseInt(maxSize.getWidth()))
                                                .setMaxHeight(Integer.parseInt(maxSize.getHeight()));
                                    }
                                }
                                if (compress != null) {
                                    builder.setMaxSize(compress.getSizeLimit() * 1024).setUnit(compress.getUnit());
                                }
                                LubanOptions compressOptions = builder.create();
                                CompressOptions config = CompressOptions.ofLuban(compressOptions);
                                takePhoto.onEnableCompress(config, true);
                            } else {
                                takePhoto.onEnableCompress(null, false);
                            }

                            Crop crop = photo.getCrop();
                            if (crop != null) {
                                CropOptions.Builder cropBuilder = new CropOptions.Builder();
                                CropOptions cropOptions = cropBuilder.setAspectX(crop.getWidthRatio()).setAspectY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                                LogUtils.d(" crop one picture with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                                takePhoto.onPickFromCaptureWithCrop(TImageFiles.getTempFileUri(), cropOptions);
                            } else {
                                takePhoto.onPickFromCapture(TImageFiles.getTempFileUri());
                            }

                        }
                        apiName = "takePicture";
                        takePictureCallBackFunction = function;

                    }
                });
        //选择多图接口 多图不支持裁剪 单图支持裁剪
        webview.registerHandler("selectPicture", (data, function) -> {
            LogUtils.d("selectPicture  data==== " + data);

            File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
            if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
            Uri imageUri = Uri.fromFile(file);
            Photo photo = (Photo) GsonUtils.json2Obj(data, Photo.class);
            if (photo != null) {

                Compress compress = photo.getCompress();
                MaxSize maxSize = photo.getMaxSize();
                if (compress != null || maxSize != null) {
                    LubanOptions.Builder builder = new LubanOptions.Builder();
                    if (maxSize != null) {
                        if (!TextUtils.isEmpty(maxSize.getWidth()) && !TextUtils.isEmpty(maxSize.getHeight())) {
                            builder.setMaxWidth(Integer.parseInt(maxSize.getWidth()));
                            builder.setMaxHeight(Integer.parseInt(maxSize.getHeight()));
                        }
                    }
                    if (compress != null) {
                        builder.setMaxSize(compress.getSizeLimit() * 1024).setUnit(compress.getUnit());
                    }
                    LubanOptions compressOptions = builder.create();
                    CompressOptions config = CompressOptions.ofLuban(compressOptions);
                    getTakePhoto().onEnableCompress(config, true);
                } else {
                    getTakePhoto().onEnableCompress(null, false);
                }
                int limit = photo.getMaxNum();
                if (limit > 1) {
                    Crop crop = photo.getCrop();
                    if (crop != null) {
                        LogUtils.d(" crop mulitule pictures with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                        CropOptions.Builder cropBuilder = new CropOptions.Builder();
                        CropOptions cropOptions = cropBuilder.setAspectX(crop.getWidthRatio()).setAspectY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                        takePhoto.onPickMultipleWithCrop(limit, cropOptions);
                    } else {
                        getTakePhoto().onPickMultiple(limit);
                    }
                } else {
                    Crop crop = photo.getCrop();
                    if (crop != null) {
                        LogUtils.d(" crop one picture with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                        CropOptions.Builder cropBuilder = new CropOptions.Builder();
                        CropOptions cropOptions = cropBuilder.setOutputX(crop.getWidthRatio()).setOutputY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                        takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                    } else {
                        takePhoto.onPickFromGallery();
                    }
                }
            }
            apiName = "selectPicture";
            selectPictureCallBackFunction = function;
        });

        //保存图片
        webview.registerHandler("savePicture", (data, function) -> {
            LogUtils.d("savePicture  data==== " + data);

            if (TextUtils.isEmpty(data))
                return;
            JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
            if (jsonObject != null && jsonObject.get("url") != null) {
                String url = jsonObject.get("url").getAsString() + "";
                savePictureCallBackFunction = function;
                if (!TextUtils.isEmpty(url)) {
                    saveImage(url);
                }

            }
        });

        webview.registerHandler("scan", (data, function) -> {
            LogUtils.d("--- scan");

            if (TextUtils.isEmpty(data))
                return;
            scanCallBackFunction = function;
            XXPermissions.with(requireActivity()).permission(Permission.CAMERA
            ).request(new OnPermission() {
                @Override
                public void hasPermission(List<String> granted, boolean isAll) {
                    dismissTopDialog();
                    Intent intent = new Intent(requireContext(), ScanActivity.class);
                    JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                    if (jsonObject != null && jsonObject.get("title") != null) {
                        String title = jsonObject.get("title").getAsString();
                        intent.putExtra("title", title);
                    }
                    if (jsonObject != null && jsonObject.get("text") != null) {
                        String title = jsonObject.get("text").getAsString();
                        intent.putExtra("text", title);
                    }
                    intent.putExtra("from", "H5Fragment");
                    startActivityForResult(intent, 5);

                }

                @Override
                public void noPermission(List<String> denied, boolean quick) {
                    dismissTopDialog();
                    HostJsScope.h5PostLocalCallBack(webview, "11", "未开启摄像头权限", false, "scan", null, scanCallBackFunction);

                }
            });
            if (!XXPermissions.isHasPermission(requireContext(), Permission.CAMERA)) {
                showTopDialog("为了您能正常使用【扫码】功能，需向您申请相机权限。如果不允许，您将无法使用扫码功能。");
            }
        });

        webview.registerHandler("authV2", (data, function) -> {
            authV2CallBackFunction = function;
            getSign();
        });
        webview.registerHandler("tradePay", (data, function) -> {
            payV2CallBackFunction = function;
            JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
            if (jsonObject != null && jsonObject.get("payType") != null) {
                String payType = jsonObject.get("payType").getAsString() + "";

                String orderInfo = jsonObject.get("orderInfo").getAsString() + "";

                if ("alipay".equals(payType)) {

                    payV2(orderInfo);
                }

            }

        });


        //图片缩放预览
        webview.registerHandler("viewPicture", (data, function) -> {
            LogUtils.d("viewPicture  data==== " + data);
            Image image = (Image) GsonUtils.json2Obj(data, Image.class);
            if (image != null) {
                Intent intent = new Intent(requireContext(), PhotoViewActivity.class);
                intent.putExtra("currentIndex", image.getCurrent());

                intent.putStringArrayListExtra("files", image.getFiles());
                startActivity(intent);
                apiName = "viewPicture";
                photoviewCallBackFunction = function;
            }
        });
        //上传文件及参数
        webview.registerHandler("uploadPicture", (data, function) -> {
            LogUtils.d("uploadPicture upload data==== " + data);
            final Upload upload = (Upload) GsonUtils.json2Obj(data, Upload.class);
            if (upload != null) {
                if (!TextUtils.isEmpty(upload.getUrl())) {
                    uploadPictureCallBackFunction = function;
                    XXPermissions.with(requireActivity()).permission(Permission.WRITE_EXTERNAL_STORAGE,
                            Permission.READ_EXTERNAL_STORAGE).request(new OnPermission() {

                        @Override
                        public void hasPermission(List<String> granted, boolean isAll) {
                            if (isAll) {
                                dismissTopDialog();
                                TUtils.uploadPictures(webview, upload.getUrl(), upload.getFile(), upload.getData());
                                apiName = "uploadPicture";
                            }
                        }

                        @Override
                        public void noPermission(List<String> denied, boolean quick) {
                            dismissTopDialog();
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "未开启存储权限", false, "uploadPicture", "", uploadPictureCallBackFunction);
                            if (uploadPictureCallBackFunction != null) {
                                uploadPictureCallBackFunction = null;
                            }
                        }
                    });
                    if (!XXPermissions.isHasPermission(requireContext(), Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)) {
                        showTopDialog("为了您能正常上传身份证，完成身份认证等功能，，需向您申请媒体文件存储权限。如果不允许，您将无法存储和取用相册图片。");
                    }

                }
            }
        });


    }

    private TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    /**
     * 保存图片
     * @param imgUrl 图片地址
     */
    private void saveImage(final String imgUrl) {
        LogUtils.d("--- saveImage : "+imgUrl);
        XXPermissions.with(requireActivity()).permission(Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE).request(new OnPermission() {

            @Override
            public void hasPermission(List<String> granted, boolean isAll) {
                if (isAll) {
                    dismissTopDialog();
                    new WriteString(imgUrl).start();
                }
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                dismissTopDialog();
                Response_Base response_base = new Response_Base();
                response_base.setResultObject(null);
                response_base.setCode("-1");
                response_base.setSuccess(false);
                HostJsScope.h5PostLocalCallBack(webview, "-1", "未开启存储权限", false, "savePicture", response_base, savePictureCallBackFunction);

            }
        });
        if (!XXPermissions.isHasPermission(requireContext(), Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE)) {
            showTopDialog("为了您能正常使用【保存图片】等功能，，需向您申请媒体文件存储权限。如果不允许，您将无法存储和取用相册图片。");
        }
    }


    private class WriteString extends Thread {

        private String url;

        public WriteString(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            super.run();
            //干你需要做的操作
            String fileUrl = FileUtils.writeFile(url);
            Response_Base response_base = new Response_Base();
            response_base.setResultObject(null);
            if (!TextUtils.isEmpty(fileUrl)) {
                response_base.setCode("0");
                response_base.setSuccess(true);
                HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "savePicture", response_base, savePictureCallBackFunction);

                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(new File(fileUrl));
                intent.setData(uri);
                requireContext().sendBroadcast(intent);
            } else {
                response_base.setCode("-1");
                response_base.setSuccess(false);
                HostJsScope.h5PostLocalCallBack(webview, "-1", "", false, "savePicture", response_base, savePictureCallBackFunction);
            }
        }
    }

    public void payV2(final String orderInfo) {
        if (!TextUtils.isEmpty(orderInfo)) {
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(requireActivity());
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "未获取到orderInfo", true,
                    "tradePay", "", payV2CallBackFunction);
            if (payV2CallBackFunction != null) {
                payV2CallBackFunction = null;
            }
        }

    }

    //获取sign 并且支付宝登录
    private void getSign() {
        showLoading("正在加载...");
        NetWorkRequset.doJoinLogin(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                String sign = (String) response_baseModel.getResultObject();
                if (!TextUtils.isEmpty(sign)) {
                    authV2(sign);
                } else {
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "未获取到sign", true, "authV2", "", authV2CallBackFunction);
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                }
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();

            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                dismissLoading();

            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, response_baseModel.getMsg(), true, "authV2", "", authV2CallBackFunction);
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                }
            }
        });
    }

    /**
     * 支付宝账户授权业务
     */
    private void authV2(final String sign) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(requireActivity());
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(sign, true);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    public void showVersionUpdate(AppVersion appVersion, final String url) {
        Intent intentDown = new Intent(requireContext(), DownLoadDialogActivity.class);
        intentDown.putExtra("url", url);
        intentDown.putExtra("autoLogin", "H5Bridge");
        intentDown.putExtra("appVersion", appVersion);
        startActivity(intentDown);
    }

    //自定义的WebViewClient
    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.i("lkf", " onPageStarted----");
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!isErrorPage) {
                hideErrorPage();
            }
            view.loadUrl("javascript:window.YzJSBridge = window.WebViewJavascriptBridge;window.YzJSBridge.call = window.YzJSBridge.callHandler;");
            view.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.READY_EVENT);");
            view.loadUrl("javascript:readyFunc();");
            loading_layout.setVisibility(View.GONE);
            dismissLoading();

        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.i("lkf", failingUrl + "onReceivedError==" + description + "     errorCode" + errorCode);
            showErrorPage();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("lkf", " shouldOverrideUrlLoading----");
            if (url.startsWith("taobao://")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);

                return true;
            }
            if (url.trim().startsWith("tel")) {
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }
            return super.shouldOverrideUrlLoading(view, url);
        }
    }

    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(requireContext());
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    private boolean isErrorPage;//默认false 说明不是错误页面

    public void showErrorPage() {
        errorLayout.setVisibility(View.VISIBLE);
        webview.setVisibility(View.GONE);
        isErrorPage = true;
    }

    public void hideErrorPage() {
        errorLayout.setVisibility(View.GONE);
        webview.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPause() {
        super.onPause();
        requireActivity().startService(new Intent(requireActivity(), PlayerMusicService.class));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (smartConfig != null) {
            smartConfig.stop();
        }
        if (webview != null) {
            webview.destroy();
        }
        if (myReceiver != null) {
            requireActivity().unregisterReceiver(myReceiver);
        }
    }
}
